import {Component} from '@angular/core';
import {App, Events, IonicPage, NavController, ViewController} from 'ionic-angular';
import {StorageProvider} from "@providers/storage";
import {DialogProvider} from "@providers/dialog";
import {AuthGuardProvider} from "@providers/auth-guard";
import {FormBuilder, Validators} from "@angular/forms";

/**
 * Generated class for the WorkerLoginPage page.
 *
 * See https://ionicframework.com/docs/components/#navigation for more info on
 * Ionic pages and navigation.
 */



@IonicPage()
@Component({
  selector: 'page-worker-login',
  templateUrl: 'worker-login.html',
})
export class WorkerLoginPage {

  hide: boolean = false;//获取焦点时隐藏下面的图片

  constructor(private app: App,
              private navCtrl: NavController,
              private formBuilder: FormBuilder,
              private authGuard: AuthGuardProvider,
              private storage: StorageProvider,
              private viewCtrl: ViewController,
              private dialog: DialogProvider,
              private events: Events,) {

  }

  loginForm = this.formBuilder.group({
    'userId': ['', [Validators.required, Validators.minLength(4)]],// 第一个参数是默认值
    'password': ['', [Validators.required, Validators.minLength(4)]],
  });

  ionViewDidLoad() {
    //this.storage.write("UserInfo",null);
  }

  login(user,_event) {
    _event.preventDefault();//该方法将通知 Web 浏览器不要执行与事件关联的默认动作
    this.dialog.showLoading();
    //let user = {userId: this.userId , password: this.password};
    this.authGuard.login(user).subscribe(data => {
      this.dialog.hideLoading();
      if (data) {
        if (this.authGuard.page) {
          this.viewCtrl.dismiss(); //销毁当前页面
          if (this.authGuard.navCtrl) {
            this.authGuard.navCtrl.push(this.authGuard.page);
          } else {
            // this.navCtrl.push(this.authGuard.page);
          }
        } else {
          let userInfo = this.storage.read('userInfo');
          if (userInfo["PAGE"] != null && userInfo["PAGE"].length != 0) {
            let str = JSON.stringify(userInfo["PAGE"]);
            if (str.indexOf("SAZYT") != -1) {
              this.app.getRootNav().setRoot("WorkerTabsPage");
            } else if (str.indexOf("THY") != -1) {
              this.app.getRootNav().setRoot("ConsigneeTabsPage");
            } else {
              this.dialog.showAlert("人员无权限");
            }
          } else {
            this.dialog.showAlert("人员无权限");
          }
        }
      }

      //登陆成功后设置需要在登陆成功后进行的事件
      this.events.publish('login');

    }, error => {
      this.dialog.hideLoading();
      this.dialog.showAlert(error);
    });

  }

  register() {
    this.navCtrl.push("WorkerRegisterPage");
  }

  forgetPassword() {
    this.navCtrl.push("WorkerForgetPasswordPage")
  }

}
